﻿using EFDBModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace EFNetCoreAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PatientController : ControllerBase
    {
        OracleDBContext dBContext;
        DbSet<Patient> Contioner;
        public PatientController(OracleDBContext context)
        {
            dBContext = context;
            Contioner = dBContext.Set<Patient>();
        }

        /// <summary>
        /// 根据id查一个患者信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public string Get(string id)
        {
            using (dBContext)
            {
                //踩坑位置，linq to sql ToList后才能过滤。
                var pat = Contioner.Where(c => c.UserId==id).ToList().SingleOrDefault();
                return pat?.Name;
            }
        }

        /// <summary>
        /// 添加一个患者信息
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public int Add()
        {
            using (dBContext)
            {
                Patient products = new Patient()
                {
                    Name = "李四",
                    UserId = "124",
                    Sex = "女",
                    AddDate = DateTime.Now
                };
                Contioner.Add(products);
                int res = dBContext.SaveChanges();
                return res;
            }
        }

        /// 添加一个患者信息
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public int Update(string id)
        {
            using (dBContext)
            {
                var pat = Contioner.Where(c => c.UserId.Equals(id)).ToList().SingleOrDefault();
                pat.Name = "更新";
                Contioner.Update(pat);
                int res = dBContext.SaveChanges();
                return res;
            }
        }

        /// <summary>
        /// 删除一个患者信息
        /// </summary>
        /// <param name="value"></param>
        [HttpDelete]
        public int Delete(string id)
        {
            using (dBContext)
            {
                var pat = Contioner.Where(c => c.UserId.Equals(id)).ToList().FirstOrDefault();
                Contioner.Remove(pat);
                int res = dBContext.SaveChanges();
                return res;
            }
        }
    }
}
